package com.atguigu.oss.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.PutObjectResult;
import com.atguigu.oss.service.OssService;
import com.atguigu.oss.utils.ConstantPropertiesUtil;
import org.joda.time.DateTime;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.FileInputStream;
import java.io.InputStream;
import java.util.Date;
import java.util.UUID;

@Service
public class OssServiceImpl implements OssService {

    //上传文件到阿里云oss
    @Override
    public String uploadFile(MultipartFile file) {

        String endpoint = ConstantPropertiesUtil.END_POINT; //地域节点
        String accessKeyId = ConstantPropertiesUtil.ACCESS_KEY_ID;  //id
        String accessKeySecret = ConstantPropertiesUtil.ACCESS_KEY_SECRET;  //秘钥
        String bucketName = ConstantPropertiesUtil.BUCKET_NAME;  //bucket名称

        try {
            // 创建OSSClient实例。
            OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

            // 上传文件流。
            //获取文件输入流
            InputStream inputStream = file.getInputStream();
            //获取文件名称
            String fileName = file.getOriginalFilename();
            //添加uuid值
            // 3er4-ee45-ert6-2345
            String uuid = UUID.randomUUID().toString().replaceAll("-","");
            fileName = uuid+fileName;

            //调用oss方法实现删除
            //第一个参数  BucketName
            //第二个参数  存到bucket里面文件路径和名称
            //第三个参数 上传文件输入流

            //获取当前日期，把当前日期转换需要格式 yyyy/MM/dd
//            new Date();
//            SimpleDateFormate
            String dateTime = new DateTime().toString("yyyy/MM/dd");
            fileName = dateTime+"/"+fileName;

            // 2020/04/11/01.jpg
            ossClient.putObject(bucketName, fileName, inputStream);

            // 关闭OSSClient
            ossClient.shutdown();

            //返回上传文件路径
            //阿里云oss文件路径是固定规则，自己拼接
            // https://edu-guli-1010.oss-cn-beijing.aliyuncs.com/01.jpg
            String url = "https://"+bucketName+"."+endpoint+"/"+fileName;

            return url;
        }catch(Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}
